<template>
    <div id="">
        <div>
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/home/welcome' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>日志管理</el-breadcrumb-item>
                <el-breadcrumb-item>日志列表</el-breadcrumb-item>
            </el-breadcrumb>
            <el-card class="box-card" style="margin-top:20px">
                <div slot="header" class="clearfix">
                    <span><i class="el-icon-edit-outline"></i>&nbsp;操作面板</span>
                    <el-button style="float: right; padding: 3px 0" type="text"><i class="el-icon-edit"></i>
                        新增商家</el-button>
                </div>
                <!-- 关键字搜索框 -->
                <div class="demo-input-suffix">
                    <el-input placeholder="请输入伴宠人/城市" prefix-icon="el-icon-search" v-model="searchForm.keywords"
                        maxlength="20" show-word-limit style="width:200px" size="small">
                    </el-input>
                    <el-button type="primary" icon="el-icon-search" style="margin-left:10px" size="small"
                        @click="loadData">搜索</el-button>
                </div>
                <template>
                    <el-table :data="tableData" stripe style="width: 100%;margin-top:20px;">
                        <el-table-column prop="d_img" label="日志图片" width="180" align="center">
                            <template slot-scope="scope">
                                <el-image :src="scope.row.d_img" style="width:80px;height:60px" fit="contain"></el-image>
                            </template>
                        </el-table-column>
                        <el-table-column prop="d_man_name" label="伴宠人" width="180" align="center">
                        </el-table-column>
                        <el-table-column prop="d_city" label="发布地点" width="180" align="center">
                        </el-table-column>
                        <el-table-column prop="d_time" label="发布时间" width="250" align="center">
                            <template slot-scope="scope">
                                <i class="el-icon-time">&nbsp;&nbsp;{{ format(scope.row.d_time) }}</i>
                            </template>
                        </el-table-column>
                        <el-table-column prop="d_detail" label="内容" width="250" align="center">
                        </el-table-column>
                        <el-table-column label="操作" width="180" align="center">
                            <template slot-scope="scope">
                                <el-button size="small" icon="el-icon-edit" @click="changeClick(scope.row)">编辑</el-button>
                                <el-button size="small" @click="handleClick(scope.row)" type="danger"
                                    icon="el-icon-delete">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>
                <el-dialog title="日志信息" :visible.sync="dialogFormVisible">
                    <el-form :model="ruleForm">
                        <el-row>
                            <el-col :span="24">
                                <el-form label-width="80px" :model="ruleForm" :rules="rules" ref="ruleForm">
                                    <el-form-item label="日志图片" prop="d_img">
                                        <el-upload class="avatar-uploader" action="http://47.92.27.111:9000/upload"
                                            :show-file-list="false" :on-success="handleAvatarSuccess"
                                            :before-upload="beforeAvatarUpload">
                                            <el-image v-if="ruleForm.d_img" :src="ruleForm.d_img" class="avatar"
                                                fit="cover"></el-image>
                                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                        </el-upload>
                                    </el-form-item>
                                    <!-- 商家信息 -->
                                    <el-form-item label="伴宠人员" prop="d_man_name">
                                        <el-input type="text" placeholder="请输入伴宠人员" v-model="ruleForm.d_man_name" />
                                    </el-form-item>
                                    <el-form-item label="发布城市" prop="d_city">
                                        <el-input type="text" placeholder="请输入发布城市" v-model="ruleForm.d_city"></el-input>
                                    </el-form-item>
                                    <el-form-item label="发布时间" prop="d_time">
                                        <el-col :span="24">
                                            <el-date-picker type="datetime" placeholder="选择日期" v-model="ruleForm.d_time"
                                                style="width: 100%;"></el-date-picker>
                                        </el-col>
                                    </el-form-item>
                                    <el-form-item label="发布内容" prop="d_detail">
                                        <el-input type="textarea" :rows="2" placeholder="请输入发布内容"
                                            v-model="ruleForm.d_detail" />
                                    </el-form-item>
                                </el-form>
                            </el-col>
                        </el-row>
                    </el-form>

                    <div slot="footer" class="dialog-footer">
                        <el-button @click="cancel">取消</el-button>
                        <el-button type="primary" @click="save('ruleForm')">保存</el-button>
                    </div>
                </el-dialog>
                <!-- 分页 -->
                <div class="page-box" style="text-align:right">
                    <el-pagination background layout="prev, pager, next" :total="total" :page-count="5"
                        :page-size="pageSize" @current-change="currentChange" @prev-click="prevClick"
                        @next-click="nextClick">
                    </el-pagination>
                </div>
            </el-card>
        </div>
    </div>
</template>

<script>
export default {

    data() {
        return {
            searchForm: {
                keywords: ""
            },
            page: 1,//当前页码
            pageSize: 4,//每页显示条数
            total: 0,
            tableData: [],
            dialogFormVisible: false,
            ruleForm: {
                d_img: "",
                d_city: "",
                d_time: "",
                d_man_name: "",
                d_detail: "",
                d_id: ""
            },
            rules: {
                d_img: [
                    {
                        required: true,
                        message: "请上传伴宠日志图片",
                        trigger: "change"
                    }
                ],
                d_man_name: [
                    {
                        required: true,
                        message: "请输入伴宠人员",
                        trigger: "blur"
                    }
                ],
                d_city: [
                    {
                        required: true,
                        message: "请输入发布城市",
                        trigger: "blur"
                    }
                ],
                d_detail: [
                    {
                        required: true,
                        message: "请输入发布内容",
                        trigger: "blur"
                    }
                ],
                d_time: [
                    {
                        required: true,
                        message: "请选择发布时间",
                        trigger: "blur"
                    }
                ]
            },
            formLabelWidth: '120px'
        }
    },
    methods: {
        // 格式化日期
        format(date) {
            return this.$moment(date).format("YYYY-MM-DD hh:mm:ss");
        },
        // 获取图片地址
        handleAvatarSuccess(res, file) {
            console.log("1111", res);
            // this.imageUrl = URL.createObjectURL(file.raw);
            this.ruleForm.d_img = res.data;
            console.log("图片地址:", this.ruleForm.d_img);
        },
        // 校验图片格式
        beforeAvatarUpload(file) {
            const isJPG =
                file.type === "image/jpeg" || file.type === "image/png";
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error("上传头像图片只能是 JPG 或者 PNG 格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传头像图片大小不能超过 2MB!");
            }
            return isJPG && isLt2M;
        },
        // 返回
        back() {
            this.$router.back();
        },
        loadData() {
            // 校验搜索关键字
            let keywords = this.searchForm.keywords.trim()
            console.log(keywords);
            if (!keywords) {
                keywords = "''"
            }
            // 封装请求路径
            let url = `${this.$api.diaryGet}/${this.page}/${this.pageSize}/${keywords}`
            console.log(url);
            // 请求后端
            this.$axios.get(url).then(res => {
                console.log(res);
                if (res?.data.code == 200) {
                    this.page = res?.data?.data?.page
                    this.pageSize = res?.data?.data?.pageSize
                    this.total = res?.data?.data?.total
                    this.tableData = res?.data?.data?.result1
                }
            }).catch(err => {
                console.log(err);
            })
            // this.filterDate()
        },
        currentChange(row) {
            console.log("currentChange" + row);
            this.page = row
            this.loadData()
        },
        prevClick(row) {
            console.log("prevClick" + row);
        },
        nextClick(row) {
            console.log("nextClick" + row);
        },
        handleClick(row) {
            const { d_id } = row
            console.log(d_id);
            this.$confirm('是否确认删除该条日志?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 删除实现
                let url = `${this.$api.diarydelete}/${d_id}`
                this.$axios.delete(url).then(res => {
                    console.log(res);
                    // token失效
                    if (res?.code === 202) {
                        this.$message.error(res?.msg)
                        this.$router.replace("/login")
                    }
                    if (res?.data?.code === 200) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        // 删除成功,更新表格数据
                        // this.$set()
                        this.loadData()
                    } else {
                        this.$message.error(res?.data?.msg)
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '删除失败'
                });
            });
        },
        changeClick(row) {
            this.dialogFormVisible = true
            const { d_img, d_city, d_time, d_man_name, d_detail, d_id } = row
            this.ruleForm.d_img = d_img
            this.ruleForm.d_city = d_city
            this.ruleForm.d_time = d_time
            this.ruleForm.d_man_name = d_man_name
            this.ruleForm.d_detail = d_detail
            this.ruleForm.d_id = d_id
        },
        save(formName) {
            this.dialogFormVisible = false
            this.$refs[formName].validate(valid => {
                if (valid) {
                    // 处理日期
                    // this.ruleForm.d_time = this.$dayjs(this.ruleForm.d_time).format("YYYY-MM-DD")
                    this.ruleForm.d_time = this.format(this.ruleForm.d_time)
                    // 这是表单校验通过
                    this.$axios
                        .post(this.$api.diaryUpdate, this.ruleForm)
                        .then(res => {
                            // token过期校验
                            if (res?.code == 202) {
                                this.$message.error(res?.msg);
                                this.$router.replace("/login");
                            }
                            if (res?.data?.code == 200) {
                                // 添加成功
                                this.$message.success(res?.data?.msg);
                                this.loadData()
                            } else {
                                this.$message.error(err);
                            }
                        })
                        .catch(err => {
                            this.$message.error(err);
                        });
                }
            });
        },
        cancel() {
            this.dialogFormVisible = false
            this.$message.error("取消修改");
        }
    },

    async mounted() {
        await this.loadData()
    }
}
</script>

<style scoped>
.el-image {
    width: 100px;
    height: 100px;
}

.el-upload {
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
}

.el-image__inner {
    width: 100%;
    height: 100%;
}

.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: "";
}

.clearfix:after {
    clear: both
}

.box-card {
    width: 100%;
}
</style>
